<?php
namespace Common\Models;
use Phalcon\Mvc\Model;
class BaseModel extends Model
{
    public $fileUrl='http://jiruanadmin.com';
    public $redis;
    public function initialize()
    {
        $this->redis = $this->getDI()->getredis();
        $dbConfig = $this->di->getConfig()->services->db;
        $this->useDynamicUpdate($dbConfig->use_dynamic_update);
        $this->setup($dbConfig->orm_options->toArray());
        $this->setReadConnectionService('dbSlave');
        $this->setWriteConnectionService('dbMaster');
    }


    public  function  get_cache($redis_key){
        $unser_redis_value = $this->redis->get($redis_key);
        return unserialize($unser_redis_value);
        //return  json_decode($this->redis->get($redis_key),TRUE);
    }

    /**
     * 设置cache
     * @param $redis_key
     * @param $redis_value
     * @param float|int $expire
     * @return mixed
     * @author dengjing
     * @date 2020/11/10 11:54
     */
    public function set_cache($redis_key,$redis_value,$expire=60*60*2){
        $redis_value_ser = serialize($redis_value);
        $this->redis->set($redis_key,$redis_value_ser);
        //$this->redis->set($redis_key,json_encode($redis_value));

        $this->redis->expire($redis_key,$expire);
        return  json_decode($this->redis->get($redis_key),TRUE);
    }

    /**
     * 删除cache
     * @param $redis_key
     * @param $redis_value
     * @param float|int $expire
     * @return mixed
     * @author dengjing
     * @date 2020/11/10 11:54
     */
    public function del_cache($redis_key){
        return $this->redis->del($redis_key);
    }

    /**
     * 获取redis缓存
     * @param $redis_key
     * @param $redis_value
     * @param float|int $expire
     * @return mixed
     * @author dengjing
     * @date 2020/11/10 11:54
     */
    public function get_geo($title,$longitude,$latitude,$km){
        $redis = new \Redis();
        $redis->connect('172.23.86.12',6379);
        $redis->auth("jiruanos@qq.com");
        return $redis->rawCommand('georadius', $title, $longitude, $latitude, $km, 'km','WITHDIST');
    }

    /**
     * 获取hash值
     * @param $redis_key
     * @param $redis_value
     * @param float|int $expire
     * @return mixed
     * @author dengjing
     * @date 2020/11/10 11:54
     */
    public function get_hash($key,$id){
        return $this->redis->hGet($key,$id);
    }

    /**
     * 设置redis锁
     * @param $redis_key
     * @param $val
     * @return mixed
     * @author dengjing
     * @date 2020/11/10 11:54
     */
    public  function set_lock($redis_key,$val){
        $res = $this->redis->setNx($redis_key,$val);
        $this->redis->expire($redis_key,1);
        return $res;
    }

}
